<?php
namespace Common\Service;

use Think\Exception;

class AlipayService
{
    private $alipay_config;

    private $reply;

    public function __construct()
    {
        vendor('alipay.AopSdk');
        $this->alipay_config = C('ALI_PAY_TEST');

    }


    /**
     * app支付
     * @param $outTradeNo string 订单号
     * @param $body string 商品描述
     * @param $totalFee int 订单金额
     * @param int $attach int 1是订单，2是活动订单，3是需求
     * @return array|bool
     * @throws \WxPayException
     */
    public function appPay($outTradeNo ,$body, $totalFee,$attach=1)
    {
        $aop = new \AopClient;
        $aop->gatewayUrl = $this->alipay_config['gateWayUrl'];
        $aop->appId = $this->alipay_config['appId'];
        $aop->rsaPrivateKey = $this->alipay_config['appPrivateKey'];
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = $this->alipay_config['alipayOpenKey'];
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new \AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        $passback_params=urlencode("type=$attach");
        $bizcontent = "{\"body\":\"$body\"," 
                        . "\"subject\": \"$body\","
                        . "\"out_trade_no\": \"$outTradeNo\","
                        . "\"timeout_express\": \"30m\"," 
                        . "\"total_amount\": \"$totalFee\","
                        . "\"product_code\":\"QUICK_MSECURITY_PAY\","
                        . "\"passback_params\":\"$passback_params\""
                        . "}";
        $request->setNotifyUrl($this->alipay_config['notifyUrl']);
        $request->setBizContent($bizcontent);
        //这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);

        //parse_str($response,$response);

        return ["payCode"=>$response];
    }

    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($sign_arr)
    {
        $buff = "";
        foreach ($sign_arr as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }


    /**
     *
     * 回调入口
     * @param bool $needSign 是否需要签名输出
     */
    final public function Handle($needSign = true)
    {
        $data=$_POST;
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->alipay_config['alipayOpenKey'];
        $flag = $aop->rsaCheckV1($data, NULL, "RSA2");
        $data['flag']=$flag;
        $log=json_encode($data);
        \Think\Log::record($log,'ALERT');

        if ($flag==true && $data['trade_status']=="TRADE_SUCCESS" || $data['trade_status']=="TRADE_FINISHED") {
            $result=$this->NotifyProcess($data);
            //dump($result);
            if ($result) {
                echo "success";exit;
            }
        }
        echo "fail";exit;
    }

    /**
     *
     * 回调方法入口
     * @param array $data 回调解释出的参数
     * @return true回调出来完成不需要继续回调，false回调处理未完成需要继续回调
     */
    private function NotifyProcess($data)
    {
        //dump($data);exit;
        $sn = $data['out_trade_no'];
        parse_str(urldecode($data['passback_params']),$type);
        $type=intval($type['type']);
        //dump($type);exit;
        switch ($type){
            case 1 :  $order = lt_get_order_by_sn($sn);break;
            case 2 :  $order = lt_get_activity_order_by_sn($sn);break;
            case 3 :  $order = get_require_order_by_sn($sn);break;
            case 4 :  $order = get_scan_pay_by_sn($sn);break;/*扫一扫支付*/
            default : $order =false;
        }
        if (!$order) {
            return false;
        }
        if ($order['status'] == 1) {
            return true;
        }
        $total_fee = $data['total_amount'] ;
        $app_id = $data['app_id'];
        
        if($app_id!=$this->alipay_config['appId'] || $data['seller_id']!=$this->alipay_config['uuId']){
            return false;
        }
        
        if (!isset($order["category"])) {
            $order["category"]=1;
        }
        

       // if ($order['total'] == 1 && $order['status'] == 0) {
        if ($order['total'] == $total_fee && $order['status'] == 0) {
            $orderData['payment_trade_no'] = $data['trade_no'];
            $orderData['paid_time'] = strtotime($data['gmt_payment']);
            $orderData['status'] = 1;
            $orderData['bank'] = $data['fund_bill_list']['fundChannel'];
            //1为订单，2是活动，3是需求, 4是扫一扫支付
            switch ($type){
                case 1: $result=D('Wxpay', 'Service')->orderNotify($order,$orderData);break;
                case 2: $result=D('Wxpay', 'Service')->orderActivityNotify($order,$orderData);break;
                case 3: $result=D('Wxpay', 'Service')->requireNotify($order,$orderData);break;
                case 4: $result=D('Wxpay', 'Service')->scanPayNotify($order,$orderData);break;
                default :$result=false;
            }
            return $result;
        } else {
            return false;
        }
    }

    /**
     * 扣除手续费
     * @param $total
     * @return mixed
     */
    private function getBalance($total){
        $total=intval($total);
        $balance=$total-sprintf('%.2f',$total*0.006);
        return $balance;
    }

}